package com.cqhilink.iot.jobstandardmanagement.services.innerservice.impl.device;

import com.alibaba.fastjson.JSON;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.cqhilink.api.common.utils.enums.RespCodeEnum;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.BackMessage;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.EntityTypeParamerMapper;
import com.cqhilink.iot.jobstandardmanagement.facade.model.Dic;
import com.cqhilink.iot.jobstandardmanagement.facade.model.EntityTypeParamer;
import com.cqhilink.iot.jobstandardmanagement.facade.service.device.JsmEntityTypeParamerService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.dic.JsmDicService;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by huangxueqian on 2017/4/28/028.
 */
public class JsmEntityTypeParamerServiceImpl implements JsmEntityTypeParamerService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private EntityTypeParamerMapper entityTypeParamerMapper;
    @Autowired
    private JsmDicService jsmDicService;

    /**
     * @param entityTypeId 设备类型ID
     * @throws Exception 根据设备类型ID 查询设备类型分类参数列表
     */
    @Override
    public List<EntityTypeParamer> getEntityTypeParamersByEtId(String entityTypeId) throws Exception {
        List<EntityTypeParamer> lists = entityTypeParamerMapper.getEntityTypeParamersByEtId(entityTypeId);
        return offsetEntityTypeParamer(lists);
    }

    /**
     * 根据ID查询数据
     *
     * @param deviceParamId
     * @return EntityTypeParamer
     */
    @Override
    public EntityTypeParamer selectByPrimaryKey(String deviceParamId) {
        return entityTypeParamerMapper.selectByPrimaryKey(deviceParamId);
    }

    /**
     * @param lists
     */
    private List<EntityTypeParamer> offsetEntityTypeParamer(List<EntityTypeParamer> lists) {
        List<EntityTypeParamer> entityTypeParamers = new ArrayList<EntityTypeParamer>();
        if (lists != null && lists.size() > 0) {
            for (EntityTypeParamer entityTypeParamer : lists) {
                if (StringUtils.isNotEmpty(entityTypeParamer.getDataSourceFromName()) || StringUtils.isNotEmpty(entityTypeParamer.getDataSourceFrom())) {
                    Dic dic = new Dic();
                    if (StringUtils.isNotEmpty(entityTypeParamer.getDataSourceFrom())) {
                        dic.setDicTableName(entityTypeParamer.getDataSourceFrom());
                    }
                    if (StringUtils.isNotEmpty(entityTypeParamer.getDataSourceFromName())) {
                        dic.setDicType(entityTypeParamer.getDataSourceFromName());
                    }
                    // 查询字典表 ， 进行字典填充数据
                    try {
                        List<Dic> dicList = jsmDicService.getDicsByType(dic);
                        if (dicList != null && dicList.size() > 0) {
                            entityTypeParamer.setDicList(dicList);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                entityTypeParamers.add(entityTypeParamer);
            }
        }
        return entityTypeParamers;
    }


    /**
     * 新增设备类型参数
     *
     * @param entityTypeParamer 设备类型参数
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> addEntityTypeParamer(EntityTypeParamer entityTypeParamer) throws Exception {
        if (entityTypeParamer == null) {
            throw new IllegalArgumentException("参数出错");
        }
        Map<String, Object> rowMap = Maps.newHashMap();
        entityTypeParamer.setStatus(BigDecimal.valueOf(0));
        entityTypeParamer.setDeviceParamId(UniqueUtil.uuid());
        try {
            String date = DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM);
            entityTypeParamer.setCreateTime(date);
            entityTypeParamer.setModifyTime(date);
            int rowCount = entityTypeParamerMapper.insert(entityTypeParamer);
            if (rowCount > 0) {
                logger.debug("新增设备参数:{}成功", entityTypeParamer);
                rowMap.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
                rowMap.put("msg", BackMessage.ADD_OK);
            } else {
                logger.debug("新增设备参数:{}失败", entityTypeParamer);
                rowMap.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
                rowMap.put("msg", BackMessage.ADD_FAIL);
            }
        } catch (Exception e) {
            logger.error("新增设备类型参数{}失败", entityTypeParamer);
            e.printStackTrace();
            throw new RuntimeException("新增参数类型失败");
        }
        return rowMap;
    }

    /**
     * 修改设备类型参数
     *
     * @param entityTypeParamer 设备类型参数
     * @return
     */
    @Override
    public Map<String, Object> updateEntityTypeParamer(EntityTypeParamer entityTypeParamer) throws Exception {
        if (entityTypeParamer == null) {
            throw new IllegalArgumentException("参数出错");
        }
        Map<String, Object> rowMap = Maps.newHashMap();
        try {
            String date = DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM);
            entityTypeParamer.setModifyTime(date);
            int rowCount = entityTypeParamerMapper.updateByPrimaryKeySelective(entityTypeParamer);
            if (rowCount > 0) {
                logger.debug("修改设备参数:{}成功", entityTypeParamer);
                rowMap.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
                rowMap.put("msg", BackMessage.ADD_OK);
            } else {
                logger.debug("修改设备参数:{}失败", entityTypeParamer);
                rowMap.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
                rowMap.put("msg", BackMessage.ADD_FAIL);
            }
        } catch (Exception e) {
            logger.error("修改设备类型参数{}失败", entityTypeParamer);
            throw new RuntimeException("修改参数类型失败");
        }
        return rowMap;
    }

    /**
     * 根据主键删除设备类型参数
     *
     * @param deviceParamId 设备类型参数ID
     * @return
     */
    @Override
    public Map<String, Object> deleteEntityTypeParamerById(String deviceParamId) throws Exception {
        if (Strings.isNullOrEmpty(deviceParamId)) {
            throw new IllegalArgumentException("参数出错");
        }
        Map<String, Object> rowMap = Maps.newHashMap();
        try {
            List<String> list = JSON.parseArray(deviceParamId, String.class);
            int rowCount = entityTypeParamerMapper.deleteListId(list);
            if (rowCount > 0) {
                logger.debug("删除设备参数类型成功,设备类型参数ID：{}", deviceParamId);
                rowMap.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
                rowMap.put("msg", BackMessage.ADD_OK);
            } else {
                logger.debug("删除设备参数类型失败,设备类型参数ID：{}", deviceParamId);
                rowMap.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
                rowMap.put("msg", BackMessage.ADD_FAIL);
            }
        } catch (Exception e) {
            logger.error("删除设备类型参数失败,设备类型参数ID：{}", deviceParamId);
            throw new RuntimeException("修改参数类型失败");
        }
        return rowMap;
    }

    /**
     * 分页查询设备类型参数
     *
     * @param entityTypeParamer 检索实体
     * @return
     */
    @Override
    public Map<String, Object> findEntityTypeParamerByPage(EntityTypeParamer entityTypeParamer) {
        Map<String, Object> resultMap = Maps.newHashMap();
        List<EntityTypeParamer> entityTypeParamerList = entityTypeParamerMapper.findEntityTypeParamerList(entityTypeParamer);
        int entityTypeParamerCount = entityTypeParamerMapper.findEntityTypeParamerCount(entityTypeParamer);
        resultMap.put("rows", entityTypeParamerList == null ? Lists.newArrayList() : entityTypeParamerList);
        resultMap.put("total", entityTypeParamerCount);
        return resultMap;
    }
}
